import java.math.BigDecimal;
import java.math.RoundingMode;

public class AverageCapital extends Capital{
    public AverageCapital(BigDecimal loanMoney, BigDecimal yearRate, int totalMonth) {
        this.loanMoney = loanMoney;
        this.yearRate = yearRate;
        this.totalMonth = totalMonth;
    }

    @Override
    public void calculate() {
        //已归还本金累计额
        BigDecimal principleHaveBeenPayed = new BigDecimal("0");
        //每月月供递减额
        BigDecimal decreasedValue = new BigDecimal("0");
        //总利息清零
        totalInterest = new BigDecimal("0");
        //月利率
        BigDecimal monthRate = yearRate.divide(new BigDecimal("12"),15,RoundingMode.HALF_UP);

        for(int i=1;i<=totalMonth;i++) {
            //setScale(0,RoundingMode.CEILING)用来设置结果向下取整
            monthPrinciple = loanMoney.divide(BigDecimal.valueOf(totalMonth),0,RoundingMode.HALF_UP)
                    .setScale(0,RoundingMode.CEILING);
            monthInterest = loanMoney
                    .subtract(principleHaveBeenPayed)
                    .multiply(monthRate)
                    .setScale(0,RoundingMode.CEILING);
            monthTotalPayment = monthPrinciple.add(monthInterest)
                    .setScale(0,RoundingMode.CEILING);
            decreasedValue = monthPrinciple.multiply(monthRate)
                    .setScale(0,RoundingMode.CEILING);
            //已偿还的本金
            principleHaveBeenPayed = principleHaveBeenPayed.add(monthPrinciple);
            //总利息
            totalInterest = totalInterest.add(monthInterest);
            System.out.println("第"+i+"月：月供额:"+monthTotalPayment+"，该月应还利息:"+monthInterest+
                    "，该月应还本金:"+monthPrinciple+"，该月月供递减额度："+decreasedValue+
                    "，已偿还本金："+principleHaveBeenPayed);
        }
        System.out.println("该还款方式总利息为"+totalInterest);

    }
}
